﻿using HandyControl.Controls;
using PlaceOrder_Admin.Extensions;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DialogResult = Prism.Services.Dialogs.DialogResult;

namespace PlaceOrder_Admin.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        private readonly IUserHelper _userHelper;
        private readonly IData _data;
        private readonly Prism.Services.Dialogs.IDialogService _dialogService;
        public static string StaticUserName = "";
        public LoginViewModel(IEventAggregator aggregator, IUserHelper userHelper, IData data,
            Prism.Services.Dialogs.IDialogService dialogService)
        {
            // 获取用户名设置
            _userHelper = userHelper;
            _data = data;
            _dialogService = dialogService;
            ExecuteCommand = new DelegateCommand<string>(Execute);
            this.aggregator = aggregator;
        }

        public string Title { get; set; } = "全益下单系统（管理端）";
        public string Icon { get; set; } = "../Images/lily.ico";


        private bool _isLoading = false;
        public bool IsLoading
        {
            get { return _isLoading; }
            set
            {
                if (_isLoading != value)
                {
                    _isLoading = value;
                    RaisePropertyChanged();
                }
            }
        }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            LoginOut();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
        }

        #region Login

        private int selectIndex;

        public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; RaisePropertyChanged(); }
        }


        public DelegateCommand<string> ExecuteCommand { get; private set; }


        private string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }
        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        private string passWord;

        private readonly IEventAggregator aggregator;



        private void Execute(string obj)
        {
            switch (obj)
            {
                case "Login": Login(); break;
                case "Cancel": LoginOut(); break;
                case "ResgiterPage": SelectIndex = 1; break;
                case "Return": SelectIndex = 0; break;
            }
        }


        async void Login()
        {
            IsLoading = true;
            string NickName = null;
            //ShowOrderView();
            //return;
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(PassWord))
            {
                Growl.Info("请输入用户名/密码", "LoginMsg");
                IsLoading = false; // 设置加载状态为 false
                return;
            }

            UserInfo userInfo = new UserInfo();
            userInfo.userName = UserName;
            userInfo.password = PassWord;

            string logMsg = string.Empty;
            var loginResult = await _userHelper.Login(userInfo);
            IsLoading = false; // 设置加载状态为 false

            if (loginResult.Item2)
            {
                //if (UserHelper.UserName != "admin")
                //{
                //    Growl.Info("请使用admin登录账户", "LoginMsg");
                //    return;
                //}
            }
            else
            {
                Growl.Error("登录异常", loginResult.Item1);
            }

            if (loginResult.Item1 != null && loginResult.Item2 == true)
            {
                UserHelper.UserID = _data.GetUserID(UserName, out NickName);
                UserHelper.NickName = NickName;

                //check有没有管理员权限
                if(!_userHelper.CheckAdminRole(UserHelper.UserID))
                {
                    string msg1 = UserHelper.NickName+ "权限不足。无法登录管理端！" ;
                    Growl.ErrorGlobal(msg1);
                    return;
                }

                string msg = "登录成功." + GetGreeting() + NickName + "~";

                StaticUserName = UserName;
                AppLog.WriteInfo(msg);
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            }
            else
            {
                string msg = "登录失败." + GetGreeting() + NickName + "~";
                AppLog.WriteError(msg);
                aggregator.SendMessage(loginResult.Item1, "Login");
            }
        }

        private string GetGreeting()
        {
            var hour = DateTime.Now.Hour;
            if (hour >= 6 && hour < 12)
            {
                return "早上好，";
            }
            else if (hour >= 12 && hour < 18)
            {
                return "中午好，";
            }
            else
            {
                return "晚上好，";
            }
        }


        void LoginOut()
        {
            //IsLoading = !IsLoading;
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));

        }

        #endregion
    }
}
